//
//  SRExpressionView.m
//  ExpressionTest
//
//  Created by Charles on 2017/1/1.
//  Copyright © 2017年 Charles. All rights reserved.
//

#import "SRExpressionView.h"
#import "SRExpressionData.h"
#import "SRExpressionDataTool.h"
static const NSInteger kRowCount = 8;
static const NSInteger kLineCount = 3;
static const NSInteger kCountPerPage = kRowCount * 3 - 1;
static const CGFloat   kExpressionWidth = 35;

@interface SRExpressionView()

@property (strong,nonatomic) NSMutableArray * expressionNumbers;

@end

@implementation SRExpressionView {
    NSInteger expressionNum;
}

- (instancetype)init {
    if (self = [super init]) {
        [self makeView];
    }
    return self;
}

- (void)makeView {
    SRExpressionData * data = [[SRExpressionData alloc]init];
    self.expressionArray = data.expressions;
    self.expressionNumbers = [[NSMutableArray alloc]initWithCapacity:0];
    float width = kExpressionWidth;
    float margin = (WIDE - kExpressionWidth * kRowCount) / (kRowCount + 1);
    float gao = width*3+margin*3+30+40;
    self.frame = CGRectMake(0, HIGH-gao, WIDE, gao);
    expressionNum = 0;
    NSInteger type = 0;
    for (SRExpressionObj*obj in self.expressionArray) {
        @synchronized (self) {
            NSInteger typeNum = obj.expressionArray.count % kCountPerPage > 0 ? obj.expressionArray.count / kCountPerPage + 1 : obj.expressionArray.count / kCountPerPage;
            [self.expressionNumbers addObject:[NSNumber numberWithInteger:typeNum]];
            [self addExpressionView:obj.expressionArray num:typeNum beginNum:expressionNum expressionType:type++];
            expressionNum += typeNum;
        }
    }
    
    SRExpressionObj*obj = self.expressionArray[0];
    NSInteger typeNum = obj.expressionArray.count % kCountPerPage > 0 ? obj.expressionArray.count / kCountPerPage + 1 : obj.expressionArray.count / kCountPerPage;
    self.defaultPage.currentPage = 0; //当前页
    self.defaultPage.numberOfPages = typeNum;//总的图片页数
    _defaultView.contentSize = CGSizeMake(WIDE*(expressionNum), width*3+margin*4);
    _selectIndex = 0;
    [self addSwitchButton];
}


/**
 添加表情tab
 */
- (void)addSwitchButton {
    
    float y = self.bounds.size.height - 39.6;
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, y-0.4, WIDE, 0.4)];
    lab.backgroundColor = [UIColor lightGrayColor];
    [self addSubview:lab];
    
    NSInteger typeCount = self.expressionArray.count + 1;
    CGFloat  typeWidth = WIDE / typeCount;
    for (NSInteger i=0; i<self.expressionArray.count; i++) {
        SRExpressionObj * obj = self.expressionArray[i];
        UIButton * expressionTypeBtn = [[UIButton alloc] initWithFrame:CGRectMake(typeWidth *i, y, typeWidth, 39.6)];
        [expressionTypeBtn addTarget:self action:@selector(selectExpressionType:) forControlEvents:UIControlEventTouchUpInside];
        [expressionTypeBtn setTitle:obj.expressionName forState:UIControlStateNormal];
        expressionTypeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [expressionTypeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        expressionTypeBtn.tag = 5000+i;
        [self addSubview:expressionTypeBtn];
        //默认选中第一个
        if (i == 0) {
            [self selectExpressionType:expressionTypeBtn];
            _selectIndex = 0;
        }
    }
    
    UIButton * sendBtn = [[UIButton alloc] initWithFrame:CGRectMake(typeWidth*(typeCount - 1), y, typeWidth, 39.6)];
    [sendBtn addTarget:self action:@selector(selectSendBtn) forControlEvents:UIControlEventTouchUpInside];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    [sendBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self addSubview:sendBtn];
}

- (void)selectSendBtn{
    if ([self.delegate respondsToSelector:@selector(srExpressionViewSend)]) {
        [self.delegate srExpressionViewSend];
    }
}

- (void)selectExpressionType:(UIButton *)sender {
    
    NSInteger index = sender.tag - 5000;
    _selectIndex = index;
    for (NSInteger i = 0; i<self.expressionArray.count; i++) {
        if (i == index) {
            SRExpressionObj * obj = self.expressionArray[index];
            NSInteger typeNum = obj.expressionArray.count % kCountPerPage > 0 ? obj.expressionArray.count / kCountPerPage + 1 : obj.expressionArray.count / kCountPerPage;
            self.defaultPage.numberOfPages = typeNum;
            [_defaultPage setCurrentPage:0];
            if (i == 0) {
                self.defaultView.contentOffset = CGPointMake(0, 0);
            }else {
                NSInteger totalNum = 0;
                for (NSInteger j = 0; j<i; j++) {
                    SRExpressionObj * obj = self.expressionArray[j];
                    NSInteger typeNum = obj.expressionArray.count % kCountPerPage > 0 ? obj.expressionArray.count / kCountPerPage + 1 : obj.expressionArray.count / kCountPerPage;
                    totalNum += typeNum;
                }
                self.defaultView.contentOffset = CGPointMake(WIDE * totalNum, 0);
            }
            [self setUpBtnSelectWithTag:sender.tag];
            break;
        }
    }
}

- (void)setUpBtnSelectWithTag:(NSInteger)tag {
    
    for (id obj in self.subviews) {
        if ([obj isKindOfClass:[UIButton class]]) {
            UIButton * sender = (UIButton *)obj;
            if (sender.tag == tag) {
                [sender setBackgroundColor:[UIColor colorWithRed:220.0/255 green:220.0/255 blue:220.0/255 alpha:1]];
            }else {
                [sender setBackgroundColor:[UIColor clearColor]];
            }
        }
    }
}

- (void)addExpressionView:(NSArray *)defaultArry num:(NSInteger)ynum beginNum:(NSInteger)beginNum expressionType:(NSInteger)type{
    //表情宽高
    float width = kExpressionWidth;
    float height = kExpressionWidth;
    //间距
    float margin = (WIDE - kExpressionWidth * kRowCount) / (kRowCount + 1);
    
    NSInteger index = 0;
    for (int i = 0 ; i < ynum ; i++) {
        for (int y = 0; y < 3 ; y++) {
            for (int u = 0 ; u < kRowCount ; u++) {
                if(y == 2 && u == (kRowCount - 1)){
                    
                    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(beginNum*WIDE+margin+(margin+width)*u+i*WIDE, (margin+height)*y+15, width, height-10)];
                    [btn setBackgroundImage:[SRExpressionDataTool ObtainBtnImage] forState:UIControlStateNormal];
                    [btn addTarget:self action:@selector(deleteExpressionAction:) forControlEvents:UIControlEventTouchUpInside];
                    [self.defaultView addSubview:btn];
                    
                }else if(index < defaultArry.count){
                    
                    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(beginNum*WIDE+margin+(margin+width)*u+i*WIDE, (margin+height)*y+10, width, height)];
                    btn.tag = (type+1)*10000+index;
                    NSLog(@"++++++++++++++++tag is %zi",btn.tag);
                    NSDictionary *dict = defaultArry[index];
                    if ([dict isKindOfClass:[NSDictionary class]]) {
                        NSString *strName = dict[@"png"];
                        UIImage *image = [SRExpressionDataTool ObtainPictureDefault:strName]?[SRExpressionDataTool ObtainPictureDefault:strName]:[SRExpressionDataTool ObtainPictureLxh:strName];
                        [btn setBackgroundImage:image forState:UIControlStateNormal];
                    }else {
                        [btn setTitle:defaultArry[index] forState:UIControlStateNormal];
                        [btn.titleLabel setFont:[UIFont systemFontOfSize:30]];
                    }
                    [btn addTarget:self action:@selector(expressionSelectAction:) forControlEvents:UIControlEventTouchUpInside];
                    [self.defaultView addSubview:btn];
                    index++;
                }
            }
        }
    }
}

- (void)deleteExpressionAction:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(srExpressionViewDelete)]) {
        [self.delegate srExpressionViewDelete];
    }
}

- (void)expressionSelectAction:(UIButton *)sender {
    NSInteger num = (sender.tag - 10000) / 10000;
    NSInteger numTag = sender.tag % 10000;
    for (NSInteger i=0; i<self.expressionArray.count; i++) {
        if (num == i) {
            SRExpressionObj * obj = self.expressionArray[i];
            if (numTag < obj.expressionArray.count) {
                id select = obj.expressionArray[numTag];
                if ([select isKindOfClass:[NSDictionary class]]) {
                    select = obj.expressionArray[numTag][@"chs"];
                }
                if (select) {
                    if ([self.delegate respondsToSelector:@selector(srExpressionViewSelect:)]) {
                        [self.delegate srExpressionViewSelect:select];
                    }
                }
            }
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.frame;
    NSInteger page = offset.x / bounds.size.width;
    NSLog(@"+++++++++page is %ld",page);
    
    //        NSInteger sumNum = 0;
    //        for (NSInteger i = 0; i<self.expressionNumbers.count; i++) {
    //            NSInteger temSumNum = 0;
    //            for (NSInteger j = 0; j< i+1; j++) {
    //                temSumNum += [self.expressionNumbers[j] integerValue];
    //            }
    //            sumNum = temSumNum;
    //            //        NSLog(@"i is %ld page is %ld num is %ld",i,page,sumNum);
    //
    //            if (page == sumNum - 1) {
    //                self.defaultPage.numberOfPages = [self.expressionNumbers[i] integerValue];
    //                _selectIndex = i;
    //                [self setUpBtnSelectWithTag:_selectIndex+5000];
    //
    //                //            NSLog(@"i is %ld page is %ld num is %ld",i,page,sumNum);
    //                break;
    //            }else if (page == sumNum){
    //                self.defaultPage.numberOfPages = [self.expressionNumbers[i+1] integerValue];
    //                _selectIndex = i+1;
    //                [self setUpBtnSelectWithTag:_selectIndex+5000];
    //
    //                //                NSLog(@"i is %ld page is %ld num is %ld",i,page,sumNum);
    //                break;
    //            }
    //        }
    
    
    for (NSInteger i = 0; i < self.expressionNumbers.count; i++) {
        NSInteger temSumNum1 = 0;
        NSInteger tempIndex1 = 0;
        NSInteger tempIndex2 = 0;
        for (NSInteger j = 0; j< i+1; j++) {
            if (j < self.expressionNumbers.count) {
                temSumNum1 += [self.expressionNumbers[j] integerValue];
                tempIndex1 = j;
            }
        }
        NSInteger temSumNum2 = 0;
        for (NSInteger j = 0; j< i+2; j++) {
            if (j < self.expressionNumbers.count) {
                temSumNum2 += [self.expressionNumbers[j] integerValue];
                tempIndex2 = j;
            }
        }
        if (page >= 0 && page < temSumNum1) {
            self.defaultPage.numberOfPages = [self.expressionNumbers[tempIndex1] integerValue];
            [self setUpBtnSelectWithTag:tempIndex1+5000];
            break;
        }else {
            if (page >= temSumNum1 && page < temSumNum2) {
                self.defaultPage.numberOfPages = [self.expressionNumbers[tempIndex2] integerValue];
                [self setUpBtnSelectWithTag:tempIndex2+5000];
                break;
            }
        }
    }
    
    
    NSInteger index = page;
    for (NSInteger i = 0; i<self.expressionNumbers.count; i++) {
        NSInteger temSumNum1 = 0;
        for (NSInteger j = 0; j< i+1; j++) {
            if (j < self.expressionNumbers.count) {
                temSumNum1 += [self.expressionNumbers[j] integerValue];
            }
        }
        NSInteger temSumNum2 = 0;
        for (NSInteger j = 0; j< i+2; j++) {
            if (j < self.expressionNumbers.count) {
                temSumNum2 += [self.expressionNumbers[j] integerValue];
            }
        }
        if (page >= temSumNum1 && page < temSumNum2) {
            index = page - temSumNum1;
            break;
        }
    }
    [_defaultPage setCurrentPage:index];
}

- (UIScrollView *)defaultView{
    if(!_defaultView){
        float width = kExpressionWidth;
        float jianju = (WIDE - kExpressionWidth * kRowCount) / (kRowCount + 1);
        _defaultView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDE, width*3+jianju*3+30)];
        _defaultView.delegate = self;
        _defaultView.pagingEnabled = YES;
        _defaultView.showsVerticalScrollIndicator = FALSE;
        _defaultView.showsHorizontalScrollIndicator = FALSE;
        [self addSubview:_defaultView];
    }
    return _defaultView;
}

- (UIPageControl *)defaultPage{
    if(!_defaultPage){
        float wid = kExpressionWidth;
        float jianju = (WIDE - kExpressionWidth * kRowCount) / (kRowCount + 1);
        _defaultPage = [[UIPageControl alloc] initWithFrame:CGRectMake(0, wid*3+jianju*3+10, WIDE, 20)];
        _defaultPage.currentPageIndicatorTintColor = [UIColor orangeColor];
        _defaultPage.pageIndicatorTintColor = [UIColor lightGrayColor];
        [self addSubview:_defaultPage];
    }
    return _defaultPage;
}

@end
